// pages/storeOpenDetail/storeOpenDetail.ts
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl: getApp().globalData.IMG_URL,
    // 自定义导航栏的高度
    statusBarHeight: getApp().globalData.statusBarHeight,
    navBarHeight: getApp().globalData.navBarHeight,
    openType: 0, // 0扫码；1点击
    // 分页数据
    showLoading: true,
    showLoadingTxt: "努力加载中...",
    pageNo: 1,
    pageSize: 200,
    isRefresh: true,
    allPages: 0,
    // 业务部分
    userInfo: {
      realname: "",
      avatar: ""
    },
    storeId: "",
    storeInfo: String,
    goodsPage: Array,
    selectedGoods: [],
    // tabs
    tab0Selected: true,
    tab1Selected: false,
    hasGoods: false,
    // 操作部分
    selectedTotalPrice: 0,
    selectedOldTotalPrice: 0,
    selectedTotalNum: 0,
    showModalStatus: false
  },
  doBack() {
    wx.navigateBack()
    // wx.disableAlertBeforeUnload({ success: function (res) { }, fail: function (errMsg) { } })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(query: any) {
    if (query != null && query.scene != null) {
      //扫码进入
      // console.error("query2: " + JSON.stringify(query))
      const scanParam = decodeURIComponent(query.scene)
      // console.error("scanParam: " + scanParam)
      let paramArr = scanParam.split('&')
      // console.error("paramArr[0]: " + paramArr[0])
      // console.error("paramArr[1]: " + paramArr[1])

      // 门店号
      let storeId = paramArr[0]
      this.setData({ storeId: storeId, openType: 0 })

      // 请求数据
      this.getStoreOpenInfo(storeId)
      this.onPullDownRefresh()

    } else {
      // 点击进入
      var pageObj = this
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('acceptDataFromOpenerPage', function (param) {
        // console.error("参数：" + JSON.stringify(param))
        let storeId = param.storeId
        // console.error("参数：storeId -》" + storeId)
        // console.error("storeId.length -》" + storeId.length)

        // console.error("参数：storeId.length > 0 -》" + JSON.stringify(param))
        pageObj.setData({ storeId: storeId, openType: 1 })
        pageObj.getStoreOpenInfo(pageObj.data.storeId)
        pageObj.onPullDownRefresh()
      })
    }

    const user = wx.getStorageSync('userInfo');
    // console.error(JSON.parse(user));
    this.setData({ userInfo: JSON.parse(user) });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //切换页面时调用API
    wx.pageScrollTo({
      scrollTop: 0
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // this.onLeftItemClick("-1")
    this.setData({ pageNo: 1, isRefresh: true })
    this.getStroeGoodsPage(this.data.pageNo, "-1")
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // console.info("更多数据 onReachBottom()")
    // // 查询用户订单
    // if (this.data.allPages > this.data.pageNo) {
    //   var pageNum = this.data.pageNo + 1;
    //   this.getStroeGoodsPage(pageNum, "-1")
    //   this.setData({ pageNo: pageNum, isRefresh: false })
    // } else {
    //   console.info("没更多数据")
    // }
  },
  getStoreOpenInfo(storeId: any): void {
    var that = this
    // const token = wx.getStorageSync('token')
    const preUrl = getApp().globalData.SERVER_URL
    const url = preUrl + "fc/store/client/anon/queryOpenInfoById"
    wx.request({
      url: url,
      method: 'GET',
      data: {
        id: storeId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
        // 'X-Access-Token': token
      },
      success(res: any) {
        wx.stopPullDownRefresh()
        if (res.data.code == 200 && res.data.result != null) {
          // storeDesImg
          var storeInfoData = res.data.result
          if (storeInfoData != null && storeInfoData.storeDesImg != null
            && storeInfoData.storeDesImg.length > 0) {
            let storeDesImgList = storeInfoData.storeDesImg.split(",");
            storeInfoData.storeDesImg = storeDesImgList
          }

          that.setData({ storeInfo: storeInfoData })

          console.error("storeInfo=> " + JSON.stringify(that.data.storeInfo))

          // wx.setNavigationBarTitle({ title: that.data.storeInfo.storeName })
          // console.error("baseImgUrl: " + that.data.baseImgUrl)
        } else {
          // wx.setNavigationBarTitle({ title: "门店信息" })
          console.error(JSON.stringify(res))
        }
      },
    })
  },
  // 获取门店商品
  getStroeGoodsPage(pageNum: number, saleClassifyId: string) {
    if ("-1" == saleClassifyId) {
      saleClassifyId = ""
    }

    console.error("pageNum ==> " + pageNum)
    console.error("saleClassifyId ==> " + saleClassifyId)

    var that = this
    const token = wx.getStorageSync('token')
    const preUrl = getApp().globalData.SERVER_URL
    const goodsPageForHomeUrl = preUrl + "fc/goods/client/anon/storeGoodsPage"
    wx.request({
      url: goodsPageForHomeUrl,
      method: 'GET',
      data: {
        saleClassifyId: saleClassifyId,
        storeId: that.data.storeId,
        pageNo: pageNum,
        pageSize: this.data.pageSize
      },
      header: {
        'content-type': 'application/json', // 默认值
        'X-Access-Token': token
      },
      success(res: any) {
        // console.error("res ==> " + JSON.stringify(res))
        wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          const length = res.data.result.records.length
          if (length > 0) {// 设置展示内容
            that.setData({ hasGoods: true, tab0Selected: true, tab1Selected: false })
          } else {
            that.setData({ hasGoods: false, tab0Selected: false, tab1Selected: true })
          }

          for (let index = 0; index < length; index++) {
            const item = res.data.result.records[index]
            if (item != null) {
              const cover = item.goodsCover;
              if (cover.includes(',')) {
                const firstIndex = cover.indexOf(',');
              const coverReal = cover.substring(0, firstIndex);
              item.goodsCover = coverReal
              } else {
                item.goodsCover = cover
              }
            }
          }
          // that.setData({ goodsPage: res.data.result.records })
          // 

          if (that.data.isRefresh) {// 刷新
            that.setData({ goodsPage: res.data.result.records })
            that.setData({ showLoading: false, showLoadingTxt: "努力加载中..." })
          } else {// 加载更多
            that.setData({ goodsPage: that.data.goodsPage.concat(res.data.result.records) })
            that.setData({ showLoading: false, showLoadingTxt: "努力加载中..." })
          }
          that.setData({ allPages: res.data.result.pages })
        } else {
          console.info(JSON.stringify(res))
        }
      },
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },
  gotoGoodsDetail(param: any): void { // 打开商品详情
    wx.navigateTo({
      url: '/pages/goods/goodsDetail/goodsDetail',
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { goodsId: param.currentTarget.dataset.id })
      }
    })
  },
  /**
   * 获取数据
   * @param tradeId 
   */
  onLeftItemClick(saleClassifyId: string) {
    // if ("-1" == saleClassifyId) {
    //   saleClassifyId = ""
    // }

    // // console.error("tradeId ==> " + tradeId)
    // var that = this
    // const token = wx.getStorageSync('token')
    // const preUrl = getApp().globalData.SERVER_URL
    // const goodsPageForHomeUrl = preUrl + "fc/goods/client/anon/storeGoodsPage"
    // wx.request({
    //   url: goodsPageForHomeUrl,
    //   method: 'GET',
    //   data: {
    //     saleClassifyId: saleClassifyId,
    //     storeId: that.data.storeId,
    //     pageNum: 1,
    //     pageSize: 100
    //   },
    //   header: {
    //     'content-type': 'application/json', // 默认值
    //     'X-Access-Token': token
    //   },
    //   success(res: any) {
    //     // console.error("res ==> " + JSON.stringify(res))
    //     wx.stopPullDownRefresh()
    //     if (res.data.code == 200) {
    //       const length = res.data.result.records.length
    //       for (let index = 0; index < length; index++) {
    //         const item = res.data.result.records[index]
    //         if (item != null) {
    //           const cover = item.goodsCover;
    //           // console.error("cover ==> " + cover)
    //           const firstIndex = cover.indexOf(',');
    //           const coverReal = cover.substring(0, firstIndex);
    //           // console.error("coverReal ==> " + coverReal)
    //           item.goodsCover = coverReal
    //         }
    //       }
    //       that.setData({ goodsPage: res.data.result.records })
    //       // console.error("tradeGoodsPage" + JSON.stringify(that.data.goodsPage))
    //     } else {
    //       console.info(JSON.stringify(res))
    //     }
    //   },
    // })
  },
  doCall(param: any) {
    var phone = param.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone,
      success: function (res) {
        console.log('拨打电话成功！');
      },
      fail: function (res) {
        console.log('拨打电话失败！');
      }
    })
  },
  doNavi(param: any) {
    const that = this

    wx.openLocation({
      latitude: that.data.storeInfo.locLat, // 纬度，范围为-90~90，负数表示南纬
      longitude: that.data.storeInfo.locLng, // 经度，范围为-180~180，负数表示西经
      scale: 15, // 缩放比例
      name: that.data.storeInfo.storeName,
      address: that.data.storeInfo.locAddress,
      success: function (r) {
        console.log(r)
      }
    })
  },
  gotoPage(param: any): void {
    let pagePath = param.currentTarget.dataset.path
    // console.error("pagePath: " + pagePath)
    wx.navigateTo({
      url: pagePath,
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据  
        res.eventChannel.emit('acceptDataFromOpenerPage', { id: "test" })
      }
    })
  },
  // 商品加购-商品列表
  buyGoodsAdd(param: any): void {
    let index: number = param.currentTarget.dataset.index
    this.goodsAdd(index)
  },
  // 商品减购-商品列表
  buyGoodsSub(param: any): void {
    let index: number = param.currentTarget.dataset.index
    this.goodsSub(index)
  },
  // 商品加购-商品列表
  buyGoodsAdd4Selected(param: any): void {
    let id: string = param.currentTarget.dataset.index
    for (let index = 0; index < this.data.goodsPage.length; index++) {
      let goods = this.data.goodsPage[index]
      console.info("goods.id -> " + goods.id)
      console.info("id -> " + id)
      if (goods.id == id) {
        console.error("相等 -> --------------------")
        this.goodsAdd(index)
      }
    }
  },
  // 商品减购-商品列表
  buyGoodsSub4Selected(param: any): void {
    let id: string = param.currentTarget.dataset.index

    for (let index = 0; index < this.data.goodsPage.length; index++) {
      let goods = this.data.goodsPage[index]

      console.info("goods.id -> " + goods.id)
      console.info("id -> " + id)

      if (goods.id == id) {
        console.error("相等 -> --------------------")

        this.goodsSub(index)
      }
    }
  },
  // 商品加购-公共方法
  goodsAdd(index: number): void {
    // console.error("加购 index = " + index)
    let buyNum: number = this.data.goodsPage[index].buyNum == undefined ? 0 : this.data.goodsPage[index].buyNum

    // console.error("shoppingCarNum：" + buyNum)
    let num = buyNum + 1

    var shoppingCarNumKey = "goodsPage[" + index + "].buyNum";
    this.setData({ [shoppingCarNumKey]: num })

    // 统计
    this.doCount();
  },
  // 商品减购-公共方法
  goodsSub(index: number): void {
    // let index: number = param.currentTarget.dataset.index
    let buyNum: number = this.data.goodsPage[index].buyNum == undefined ? 0 : this.data.goodsPage[index].buyNum

    console.error("buyNum index->" + index)
    console.error("buyNum 1->" + buyNum)
    if (buyNum > 0) {
      let num = buyNum - 1
      var shoppingCarNumKey = "goodsPage[" + index + "].buyNum";
      this.setData({ [shoppingCarNumKey]: num })
      console.error("buyNum 2->" + num)
    } else {
      var shoppingCarNumKey = "goodsPage[" + index + "].buyNum";
      this.setData({ [shoppingCarNumKey]: 0 })

      console.error("buyNum 3->" + 0)
    }

    // 统计
    this.doCount();
  },
  // 商品减购-清除所有
  buyGoodsClearAll(): void {
    for (let index = 0; index < this.data.goodsPage.length; index++) {
      var shoppingCarNumKey = "goodsPage[" + index + "].buyNum";
      this.setData({ [shoppingCarNumKey]: 0 })
    }
    // 统计
    this.doCount();
  },
  // 计算
  doCount() {
    var totalPrice = 0
    var totalPriceOld = 0
    var selectedNum = 0
    var selectedGoodsTemp = []

    // console.error("goodsPage = " + JSON.stringify(this.data.goodsPage))

    for (let index = 0; index < this.data.goodsPage.length; index++) {
      let goods = this.data.goodsPage[index]

      // console.error("goods.buyNum != undefined 前" + goods.buyNum)
      if (goods.buyNum != undefined && goods.buyNum != 0) {
        // console.error("goods.buyNum != undefined 中" + goods.buyNum)
        // 加入选中集合中
        selectedGoodsTemp.push(goods)

        // console.error("goods.buyNum != undefined：goods.goodsSalePrice=" + goods.goodsSalePrice)
        // 当前销售总价
        totalPrice = totalPrice + goods.buyNum * goods.goodsSalePrice

        // 原价计算  取最大值
        let flagPrice = goods.goodsFlagPrice > goods.goodsSalePrice ? goods.goodsFlagPrice : goods.goodsSalePrice
        // 原总价
        totalPriceOld = totalPriceOld + goods.buyNum * flagPrice
        // 选中数量
        selectedNum = selectedNum + goods.buyNum
      }
    }

    // console.error("doCount().totalPrice = " + totalPrice.toFixed(2))
    // 更新数据
    this.setData({
      selectedTotalPrice: new Number(totalPrice.toFixed(2)).valueOf(),
      selectedOldTotalPrice: new Number(totalPriceOld.toFixed(2)).valueOf(),
      selectedTotalNum: selectedNum,
      selectedGoods: selectedGoodsTemp
    })

    // if (selectedNum == 0) {
    //   this.hideModal()
    //   // 没选中时,取消监听返回
    //   wx.disableAlertBeforeUnload({ success: function (res) { }, fail: function (errMsg) { } })
    // } else {
    //   // 有选中时,监听返回
    //   wx.enableAlertBeforeUnload({
    //     message: "已经选择 " + selectedNum + " 份商品，确定关闭吗？", success: function (res) { }, fail: function (errMsg) { }
    //   });
    // }
    // console.error("setData = " + JSON.stringify(this.data))
  },
  showOrderList() {
    if (this.data.selectedTotalNum == 0) {
      wx.showToast({ title: '请先选择商品', icon: 'error', duration: 2000 })
      return
    }
    this.showModal()
  },
  doSubmitOrder() {
    if (this.data.selectedTotalNum == 0) {
      wx.showToast({ title: '请先选择商品', icon: 'error', duration: 2000 })
      return
    }

    let that = this
    console.error("提交：doSubmitOrder")
    let pagePath = "/pages/order/orderSubmite/orderSubmite"
    wx.navigateTo({
      url: pagePath,
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据  
        res.eventChannel.emit('acceptDataFromOpenerPage', { selectedGoods: that.data.selectedGoods, storeInfo: that.data.storeInfo })
      }
    })
  },

  showModal: function () {// 显示遮罩层
    if (this.data.showModalStatus) {
      this.hideModal()
      return
    }
    let that = this
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    // this.animation = animation
    animation.translateY(300).step()
    that.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }.bind(that), 200)
  },
  hideModal() {// 隐藏遮罩层
    let that = this
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    // this.animation = animation
    animation.translateY(300).step()
    that.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(that), 200)
  },
  switchTab(param: any) {
    let index: String = param.currentTarget.dataset.index
    switch (index) {
      case "0":
        // console.error("switchTab data case 0")
        this.setData({ tab0Selected: true, tab1Selected: false })
        break;
      case "1":
        // console.error("switchTab data case 1")
        this.setData({ tab0Selected: false, tab1Selected: true })
        break;
      default:
        // console.error("switchTab data default")
        break;
    }
  }
})